package com.quxue.im.util;

import com.quxue.im.common.enums.SmsTypeEnum;
import com.quxue.im.exception.LogicException;
import com.quxue.im.vo.AjaxResult;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.quxue.im.common.enums.SmsTypeEnum.*;

@Component
public class SmsUtils {

    @Resource
    private RedisUtils redisUtils;

    public void sendSms(String phone, String code, int type){

        String key  = getPrefix(type)+phone;

        //发送数据到redis，5分钟秒有效
        redisUtils.set(key, code,5, TimeUnit.MINUTES);
        //TODO 调用第三方短信发送服务（阿里，腾讯，等）
    }


    public String getPrefix(int type){
        String prefix = "";
        if (REGISTER.getType() == type) {
            prefix = "register:";
        } else if (LOGIN.getType() == type) {
            prefix = "login:";
        } else if (FORGET.getType() == type) {
            prefix = "forget:";
        }
        return prefix;
    }


    public void verifySms(String phone,String code,int type){

        String key = getPrefix(type)+phone;

        if(!redisUtils.hasKey(key)){
            throw new LogicException("验证码已过期，请重新获取");
        }
        //获取随机码
        String redisCode = redisUtils.get(key);
        if(!redisCode.equals(code)){
            throw new LogicException("验证码不正确");
        }

    }
}
